package hos.java.convert;


import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;

import hos.java.util.AnyUtils;


/**
 * <p>Title: NetConverter </p>
 * <p>Description: 类型转换 </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @version : 1.0
 * @date : 2021/10/12 15:22
 */
public interface NetConverter {

    <R> R onConvert(Type succeed, Object response) throws IOException;

    default <R> R parseJson(Type succeed, String json) throws IOException {
        return onConvert(succeed, json);
    }

    class ConvertException extends IOException {

        private Object response;

        public ConvertException(Object response, String message) {
            super(message);
            this.response = response;
        }

        public ConvertException(Object response, String message, Throwable cause) {
            super(message, cause);
            this.response = response;
        }

        public ConvertException(String message) {
            super(message);
        }

        public ConvertException(String message, Throwable cause) {
            super(message, cause);
        }

        public Object getResponse() {
            return response;
        }
    }

    static <R> R convert(Type succeed, Object response) throws IOException {
        return new NetConverter.DEFAULT().onConvert(succeed, response);
    }

    class DEFAULT implements NetConverter {


        @SuppressWarnings("unchecked")
        @Override
        public <R> R onConvert(Type succeed, Object response) throws IOException {
            if (AnyUtils.isEmpty(response)) {
                return null;
            }
            if (succeed == String.class) {
                return (R) AnyUtils.toNullString(response);
            }
            if (succeed == Integer.class) {
                return (R) AnyUtils.toNullInteger(response);
            }
            if (succeed == Long.class) {
                return (R) AnyUtils.toNullLong(response);
            }
            if (succeed == Float.class) {
                return (R) AnyUtils.toNullFloat(response);
            }
            if (succeed == Double.class) {
                return (R) AnyUtils.toNullDouble(response);
            }
            if (succeed == Boolean.class) {
                return (R) AnyUtils.toNullBoolean(response);
            }
            if (succeed == File.class) {
                return (R) response;
            }
            throw new ConvertException(response + "An exception occurred while converting the NetConverter.DEFAULT");
        }
    }
}
